<template>
  <view class="wallpaper-detail">
    <!-- 顶部导航栏 -->
    <view class="wallpaper-detail__header" :style="{ top: statusBarHeight + 'px' }">
      <view class="back-btn" @click="goBack">
        <text class="icon tn-icon-left"></text>
      </view>
    </view>
    
    <!-- 壁纸展示区域 -->
    <view class="wallpaper-detail__content">
      <image 
        :src="wallpaperInfo.image_url" 
        mode="aspectFill"
        class="wallpaper-detail__image"
        @click="handlePreview"
      />
      
      <!-- 底部信息栏 -->
      <view class="wallpaper-detail__info">
        <view class="info-header">
          <view class="info-title">{{(wallpaperInfo.tags[0] || '') +'壁纸'}}</view>
          <view class="download-count">
            <text class="icon tn-icon-download"></text>
            <text>{{wallpaperInfo.download_num || 0}}</text>
          </view>
        </view>
        
        <view class="info-tags">
          <text 
            class="tag-item"
            v-for="(tag, index) in (wallpaperInfo.tags || [])"
            :key="index"
          >
            {{tag}}
          </text>
        </view>
        
        <view class="download-btn" @click="handleDownload">
          <text class="icon tn-icon-download"></text>
          下载壁纸
        </view>
      </view>
    </view>

    <!-- 保存成功提示 -->
    <view class="success-popup" :class="{ 'show': showSuccessPopup }">
      <view class="success-content">
        <text class="icon tn-icon-checkmark-circle"></text>
        <text class="text">保存成功</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getWallpaperDetail, updateWallpaperDownloads } from '@/api/wallpaper.js'

export default {
  data() {
    return {
      wallpaperInfo: {},
      isLiked: false,
      statusBarHeight: 0,
      showSuccessPopup: false,
      wallpaperId: ''
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.wallpaperId = options.id
      this.loadWallpaperDetail(options.id)
    }
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync()
    // #ifdef MP-WEIXIN
    const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
    this.statusBarHeight = menuButtonInfo.top
    // #endif
    // #ifndef MP-WEIXIN
    this.statusBarHeight = systemInfo.statusBarHeight
    // #endif
  },
  
  methods: {
    // 返回上一页
    goBack() {
      const pages = getCurrentPages()
      if (pages.length > 1) {
        uni.navigateBack()
      } else {
        // 如果没有上一页，返回壁纸列表页
        uni.redirectTo({
          url: '/resourcePages/wallpaper/wallpaperList'
        })
      }
    },
    
    // 切换收藏状态
    toggleLike() {
      this.isLiked = !this.isLiked
      uni.showToast({
        title: this.isLiked ? '已添加到收藏' : '已取消收藏',
        icon: 'none'
      })
    },
    
    // 加载壁纸详情
    async loadWallpaperDetail(id) {
      try {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        
        const res = await getWallpaperDetail(id)
        res.data.tags && (res.data.tags = res.data.tags.split(','))
        this.wallpaperInfo = res.data || {}
        
      } catch(e) {
        console.error('获取壁纸详情错误:', e)
        uni.showToast({
          title: e.message || '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 预览图片
    handlePreview() {
      uni.previewImage({
        urls: [this.wallpaperInfo.image_url],
        current: this.wallpaperInfo.image_url
      })
    },
    
    // 显示保存成功提示
    showSuccessToast() {
      this.showSuccessPopup = true
      setTimeout(() => {
        this.showSuccessPopup = false
      }, 1500)
    },
    
    // 下载壁纸
    async handleDownload() {
      try {
        // 检查保存到相册的权限
        const auth = await this.checkPhotoAuth()
        if (!auth) {
          uni.showModal({
            title: '提示',
            content: '需要您授权保存图片到相册',
            success: (res) => {
              if (res.confirm) {
                // 打开设置页面
                uni.openSetting()
              }
            }
          })
          return
        }

        uni.showLoading({
          title: '下载中...',
          mask: true
        })
        
        // 下载文件
        const [downloadError, downloadRes] = await uni.downloadFile({
          url: this.wallpaperInfo.image_url
        }).catch(err => [err, null])

        if (downloadError || downloadRes.statusCode !== 200) {
          throw new Error('下载失败')
        }

        // 保存到相册
        const [saveError] = await uni.saveImageToPhotosAlbum({
          filePath: downloadRes.tempFilePath
        }).catch(err => [err])

        if (saveError) {
          throw new Error('保存失败')
        }

        // 更新下载量
        await updateWallpaperDownloads(this.wallpaperId)

        this.showSuccessToast()

      } catch (error) {
        console.error('下载错误:', error)
        uni.showModal({
          title: '下载失败',
          content: error.message || '请稍后重试',
          showCancel: false
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 检查相册权限
    async checkPhotoAuth() {
      // #ifdef MP-WEIXIN
      const [error, res] = await uni.authorize({
        scope: 'scope.writePhotosAlbum'
      }).catch(err => [err, null])

      if (error) {
        const setting = await uni.getSetting()
        // 如果是第一次拒绝，可以继续请求授权
        if (setting.authSetting['scope.writePhotosAlbum'] === false) {
          return false
        }
        // 如果之前已授权，返回true
        return setting.authSetting['scope.writePhotosAlbum'] === true
      }
      return true
      // #endif

      // #ifndef MP-WEIXIN
      return true
      // #endif
    }
  }
}
</script>

<style lang="scss" scoped>
.wallpaper-detail {
  height: 100vh;
  background-color: #f8f8f8;
  position: relative;
  overflow: hidden;
  
  &__header {
    position: fixed;
    left: 0;
    right: 0;
    z-index: 99;
    height: 44px;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    
    .back-btn {
      width: 72rpx;
      height: 72rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(255, 255, 255, 0.8);
      border-radius: 50%;
      backdrop-filter: blur(10px);
      
      .icon {
        font-size: 36rpx;
        color: #333;
      }
      
      &:active {
        opacity: 0.9;
      }
    }
  }
  
  .like-btn {
    position: absolute;
    top: 30rpx;
    right: 30rpx;
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
    z-index: 10;
    
    .icon {
      font-size: 40rpx;
      color: #666;
      
      &.active {
        color: #FFD700;
      }
    }
    
    &:active {
      transform: scale(0.95);
    }
  }
  
  &__content {
    position: relative;
    height: 100%;
  }
  
  &__image {
    width: 100%;
    height: 100vh;
    display: block;
    object-fit: cover;
  }
  
  &__info {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.98);
    padding: 30rpx;
    padding-bottom: calc(env(safe-area-inset-bottom));
    border-radius: 40rpx 40rpx 0 0;
    
    .info-header {
      margin-bottom: 36rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .info-title {
        font-size: 40rpx;
        font-weight: 600;
        color: #333;
      }

      .download-count {
        display: flex;
        align-items: center;
        font-size: 28rpx;
        color: #666;
        
        .icon {
          font-size: 32rpx;
          margin-right: 8rpx;
        }
      }
    }
    
    .info-tags {
      display: flex;
      flex-wrap: wrap;
      margin: 0 -8rpx;
      margin-bottom: 36rpx;
      
      .tag-item {
        padding: 12rpx 24rpx;
        background-color: #F5F5F5;
        border-radius: 100rpx;
        font-size: 26rpx;
        color: #666;
        margin: 8rpx;
      }
    }
    
    .download-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 96rpx;
      background-color: #222;
      border-radius: 16rpx;
      color: #fff;
      font-size: 32rpx;
      font-weight: 500;
      margin-bottom: 20rpx;
      
      .icon {
        font-size: 36rpx;
        margin-right: 10rpx;
      }
      
      &:active {
        opacity: 0.9;
      }
    }
  }

  .success-popup {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%) scale(0.8);
    z-index: 999;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
    
    &.show {
      opacity: 1;
      visibility: visible;
      transform: translate(-50%, -50%) scale(1);
    }
    
    .success-content {
      background: rgba(0, 0, 0, 0.8);
      backdrop-filter: blur(10px);
      padding: 40rpx;
      border-radius: 24rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .icon {
        font-size: 80rpx;
        color: #fff;
        margin-bottom: 20rpx;
      }
      
      .text {
        font-size: 28rpx;
        color: #fff;
        font-weight: 500;
      }
    }
  }
}
</style>